package org.zhuzx.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Deprecated//线程安全问题
public enum TimeFormat {
	STANDARD("yyyy-MM-dd HH:mm:ss"),
	WITH_MILLIS("yyyy-MM-dd HH:mm:ss.S"),
	ALL_NUMBER("yyyyMMddHHmmss"),
	DATE("yyyy-MM-dd"),
	DATE_SLASH("yyyy/MM/dd"),
	DATE_NUMBER("yyyyMMdd"),
	TIME("HH:mm:ss"),
	TIME_NUMBER("HHmmss");
	
	
	private String pattern;
	private SimpleDateFormat dateFormat;
	
	private TimeFormat(String pattern) {
		this.pattern = pattern;
		this.dateFormat = new SimpleDateFormat(pattern);
	}
	public String getPattern() {
		return this.pattern;
	}
	public SimpleDateFormat getDateFormat() {
		return this.dateFormat;
	}
	public Date parse(String timeStr) throws ParseException {
		return this.dateFormat.parse(timeStr);
	}
	
	
	private static final TimeFormat[] values = values();
	private static final Map<String,TimeFormat> formats = getPatterns();
	private static final String SEPARATOR = "-| |:|/|\\.";
	private static Map<String,TimeFormat> getPatterns() {
		Map<String,TimeFormat> map = new LinkedHashMap<String,TimeFormat>(values.length);
		for (TimeFormat timeFormat : values) {
			map.put(timeFormat.getPattern(), timeFormat);
		}
		return map;
	}
	
	
	public static TimeFormat getTimeFormat(String pattern) {
		return formats.get(pattern);
	}
	
	public static Date chainParse(String timeStr) {
		for (TimeFormat tf : values) {
			try {
				return tf.parse(timeStr);
			} catch (ParseException e) {
				continue;
			}
		}
		String[] fields = timeStr.split(SEPARATOR);
		if (fields.length==6) {
			try {
				int[] ifs = new int[fields.length];
				for (int i=0; i<fields.length; i++) {
					ifs[i] = Integer.parseInt(fields[i]);
				}
				Calendar cale = Calendar.getInstance();
				cale.set(ifs[0], ifs[1]-1, ifs[2], ifs[3], ifs[4], ifs[5]);
				return cale.getTime();
			} catch (Exception e) {
				return null;
			}
		}
		return null;
	}
	
	public static String format(String timeStr, String pattern) {
		TimeFormat tf = getTimeFormat(pattern);
		SimpleDateFormat sdf = (tf==null) ? (new SimpleDateFormat(pattern)) : tf.getDateFormat();
		return sdf.format(chainParse(timeStr));
	}
	
	public static String format(String timeStr) {
		return STANDARD.getDateFormat().format(chainParse(timeStr));
	}
	
}